﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Net.Mail;
using System.Net;
using System.IO;
using System.Diagnostics;
using System.Configuration;
using System.Collections.Specialized;



namespace SYADynamicDNSUpdater
{
    class StatusChecker
    {
        EventLog eventLogsc { get; set; }
        string UrlChecker { get; set; }
        string CurrentIP  { get; set; }
        string QueriedIP { get; set; }
        string EmailServer { get;set; }
        string FromEmail { get;set; }
        string ToEmail { get; set;}
        string StartString { get;set; }
        string EndString { get;set; }
        int StartOffset { get; set;}
        int EndOffset { get;set; }

            

        public StatusChecker()
        {

            UrlChecker = SYADynamicDNSUpdater.Properties.Settings.Default.urlChecker;// @"http://checkip.mtgsy.net";// ConfigurationManager.AppSettings["urlChecker"];
            CurrentIP = SYADynamicDNSUpdater.Properties.Settings.Default.currentIP;//@"75.115.140.0";// ConfigurationManager.AppSettings["currentIP"];
            EmailServer = SYADynamicDNSUpdater.Properties.Settings.Default.emailServer;// @"entsrv1.drumm.us";// ConfigurationManager.AppSettings["emailServer"];
            FromEmail = SYADynamicDNSUpdater.Properties.Settings.Default.fromEmail;//@"paul@drumm.us";// ConfigurationManager.AppSettings["fromEmail"];
            ToEmail = SYADynamicDNSUpdater.Properties.Settings.Default.toEmail;//@"paul@drumm.us";// ConfigurationManager.AppSettings["toEmail"];
            StartString = SYADynamicDNSUpdater.Properties.Settings.Default.startString;// @"body";//ConfigurationManager.AppSettings["startString"];
            EndString = SYADynamicDNSUpdater.Properties.Settings.Default.endString;//@"/body";//ConfigurationManager.AppSettings["endString"];
            StartOffset = SYADynamicDNSUpdater.Properties.Settings.Default.startOffset;// 39;//Int32.Parse( ConfigurationManager.AppSettings["startOffset"]);
            EndOffset =  SYADynamicDNSUpdater.Properties.Settings.Default.endOffset;//1;//Int32.Parse( ConfigurationManager.AppSettings["endOffset"]);
            //make a DNS request to validated IP
            //get initial ipcheck

        }

        public void CheckIP(EventLog eventLog1)
        {
            eventLogsc = eventLog1;
            
            doRequest();
            //read result
            //update DNS if necessary
        }

        public void UpdateDNS()
        {
            //post dns update
        }

        private void doRequest()
        {
            //add to config the website to get the IP address from.

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(UrlChecker);

            // Set some reasonable limits on resources used by this request
            request.MaximumAutomaticRedirections = 4;
            request.MaximumResponseHeadersLength = 4;
            // Set credentials to use for this request.
           // request.Credentials = CredentialCache.DefaultCredentials;
            HttpWebResponse response = (HttpWebResponse)request.GetResponse ();

            //eventLogsc.WriteEntry("Content length is : "+ response.ContentLength.ToString());
           // Console.WriteLine ("Content type is : " + response.ContentType);

            // Get the stream associated with the response.
            Stream receiveStream = response.GetResponseStream ();

            // Pipes the stream to a higher level stream reader with the required encoding format. 
            StreamReader readStream = new StreamReader (receiveStream, Encoding.UTF8);

            QueriedIP = gleamIP(readStream.ReadToEnd());
            //eventLogsc.WriteEntry("Response stream received.");
            eventLogsc.WriteEntry("Queried IP is "+QueriedIP);
            response.Close ();
            readStream.Close ();
            if (QueriedIP != CurrentIP)
            {
                sendEmail();
            }
        }

        private string gleamIP(string IPin)
        {

            int start = IPin.IndexOf(StartString)+StartOffset;
            int end=IPin.IndexOf(EndString)-EndOffset;
           // eventLogsc.WriteEntry(start.ToString() + ":" + end.ToString());
            return IPin.Substring(start,end-start);
        }

        private void sendEmail()
        {
            SmtpClient sc = new SmtpClient(EmailServer);
           sc.Send(FromEmail,ToEmail, "IP Address Changed to " + QueriedIP,QueriedIP);
           eventLogsc.WriteEntry("IP Address Changed to "+QueriedIP,EventLogEntryType.Error);
        }

       


    }
}
